

import axios from "axios";
import { Message } from "tdesign-mobile-react";
import Cookies from "js-cookie";


const baseURL = "http://127.0.0.1";
const API = {
    APP_IMG_CODE: baseURL + "/m/code"
}

axios.defaults.baseURL = baseURL;// 默认配置
axios.defaults.timeout = 2400;// 默认
axios.defaults.withCredentials = false;
// 拦截器
axios.interceptors.request.use(function (config) {
    let token = Cookies.get("token");
    if (token) {
        config.headers.Token = token;
    }
    return config;
}, function (err) {
    return Promise.reject(err);
});
axios.interceptors.response.use(function (res) {
    return res.data;
}, function (err) {
    Message.error({
        align: "center",
        closeBtn: true,
        marquee: true,
        defaultVisible: true,
        content: "服务器错误" + err
    });
    return Promise.reject(err);
});
// 判断对象是否为空或者undefine
const is_null = (obj) => obj === null || obj === undefined;
// 判断为函数
const is_function = (fun) => !is_null(fun) && typeof fun === "function";



// 网络请求模块
const NET = {
    /**
     * 
     * @param {*} url 网络请求地址
     * @param {*} option {
     *  headers: obj 请求头
     *  data:obj 树蕨
     *  signal:new AbortController() 取消请求控制器 xx.abort()
     * }
     */
    post(url, option) {
        if (!option) { return null; }
        let _formData = undefined;
        if (option.data) {
            _formData = JSON.stringify(option.data);
        }
        return axios({
            url,
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            data: _formData,
            signal: option?.signal || null
        });
    },
    get(url) {
        return axios.get(url);
    }
}
// 设备尺寸
const DEVICE = {
    get_screen_size(call) {
        if (window && call && typeof call === "function") {
            let width = window.innerWidth;
            let height = window.innerHeight;
            call({
                width,
                height
            });
        }
    }
}
const STR = {
    not_empty(str = null) {
        return !is_null(str) && !this.is_empty(str);
    },
    is_empty(str = null) {
        if (typeof str !== "string") {
            throw TypeError("输入参数必须为字符串");
        }
        return is_null(str) || str.replaceAll(" ", "").length === 0;
    },
    remove_blank(str = null) {
        if (this.not_empty(str)) {
            return str.replaceAll(" ", "");
        } else {
            return "";
        }
    }
}
/**
 * 正则验证
 */
const REG = {
    __com(str, reg) {
        if (str && reg) {
            const regx = reg.test(str);
            return regx;
        }

    },
    __phone: /^1[3-9]\d{9}$/,
    // 手机验证 number 必填
    phone(number = null, call) {
        if (!is_null(number) && typeof number === "string" && STR.not_empty(number)) {
            if (number.length < 11) {
                this.__call_back({
                    code: 500,
                    type: "error",
                    msg: "手机号位数错误"
                }, call)
            } else {
                let res = this.__com(number, this.__phone);
                if (res) {
                    this.__call_back({
                        code: 200,
                        type: "success",
                        msg: "验证通过"
                    }, call)
                } else {
                    this.__call_back({
                        code: 400,
                        type: "error",
                        msg: "手机号格式错误"
                    }, call)
                }
            }
        }
    },
    __call_back(opt, call) {
        const { code, type, msg } = { ...opt };
        if (is_function(call)) {
            call({
                code,
                type,
                msg
            })
        } else {
            return {
                code,
                type,
                msg
            }
        }
    }
}
/**
 * 常用工具
 * 
 */
const TOOL = {
    debounce(func, delay) {
        let timer = null;
        return function (...args) {
            clearTimeout(timer);
            timer = setTimeout(() => {
                func.apply(this, args);
            }, delay);
        };
    },
    throttle(func, delay) {

        let timer = null;
        let lastTime = 0;
        return function (...args) {
            const now = Date.now();
            const remaining = delay - (now - lastTime);
            console.log(11);
            if (remaining <= 0 || remaining > delay) {
                // 立即执行
                if (timer) {
                    clearTimeout(timer);
                    timer = null;
                }
                func.apply(this, args);
                lastTime = now;
            } else if (!timer) {
                // 延迟执行最后一次
                timer = setTimeout(() => {
                    func.apply(this, args);
                    lastTime = Date.now();
                    timer = null;
                }, remaining);
            }
        };

        // let lastTime = 0;
        // return function (...args) {
        //     const now = Date.now();
        //     if (now - lastTime >= delay) {
        //         func.apply(this, args);
        //         lastTime = now;
        //     } else {
        //         if (toast && is_function(toast)) {
        //             toast.apply(this, args);
        //         }
        //     }
        // };
    }
}

export default {
    NET,
    DEVICE,
    STR,
    REG,
    API,
    TOOL
}